function [ encodedMsg ] = WiSiL_Encoder_crc(message,poly)

%%%%
% This function attaches the Cyclic Redundancy Check sequence at a binary 
% message.
% The CRC is the remainder of the Galois Field division (GF(2)):
% message/poly, where 'message' represents the signal in which the CRC will
% be applied, and poly is the generator polynomial for the CRC.
%
% Syntax:
%   -[ encodedMsg ] = CRC(message,poly) 
% Inputs Parameters:
%   -message: Message Signal. It must be represented in a binary form.
%   -poly: Generator Polynomial for the CRC. It must be represented in a
%   binary form, with the MSB at left.
% Output Parameters:
%    -encodedMsg: Is the messageSignal+CRC attached. Its length is M+N-1, where M is
%    the length of the message and N is the length of the poly.

% History:
% Rafhael Medeiros de Amorim ( rma.petit@gmail.com )
% February 12th, 2009.

%  Finding possible null bits:
auxiliar = isnan( message );
temp = find( auxiliar == 1 );
%

% Dealing with possible null bits (considering them equal to zero):
message(temp) = 0;
%

% Forcing the message to be a row vector
if ( size( message , 1 ) > size( message , 2 )) 
    message= message';
end
%
% % %%%%%%%%%%%%%%%%%%%%%% MATLAB CODE - USE WHEN NOT USING THE MEX FUNCTION %
% % %Preliminar version of encodedMsg:
% % encodedMsg = [message zeros( 1, length(poly) - 1 )];
% % %
% % 
% % %Auxiliar variable:
% % R = encodedMsg;
% % %
% % 
% % % Galois Field Division.
% % while( true )
% %     
% %     Q = find(R ~=0,1); %Finding the maximum order of the reminder.
% % 
% %     if ( isempty(Q) || length(encodedMsg)-Q<length(poly) - 1)
% %         %Stop the division if the order of the reminder is smaller than the
% %         %order of the poly:
% %         break; 
% %     else
% %         %Obtaining the new remainder for the current step of the division:
% %         R(Q:Q+length(poly)-1)=bitxor(R(Q:Q+length(poly)-1),poly);
% %     end
% % end
% % %
% % 
% % 
% % % Attaching the CRC at the Signal Message.
% % encodedMsg = bitor(encodedMsg,R);
% % 
% % %%%%%%%%%%%%%        END OF MATLAB CODE


%%%%%%%%%%%%%%%% MEX CODE - USE WHEN NOT USING THE MATLAB CODE FOR CRC %%%%
% Set Parameters to the Mex Function
polySize = length(poly); % Generator Polinomial Size      
msgSize = length(message) + polySize - 1; % Message Size
encodedMsg = [message zeros( 1, length(poly) - 1 )]; %Pre Allocating Encoded Message

R = crccore(encodedMsg,poly,msgSize,polySize); % MEX FUNCTION
encodedMsg = [message R]; % Encoded Message

% Null Bits are again positioned at the message:
encodedMsg(temp) = NaN;
%
